// pages/product/productDetails.js
var Zan = require('../../dist/index');
var WxParse = require('../../wxParse/wxParse.js');
var network = require('../../utils/network_util.js');
var utils = require('../../utils/utils.js');
var api = require('../../utils/api.js');
const app = getApp();
var eventStatus = 0; // 0=没选规格;1=加入购物车;2=立即购买

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    listSpec: [],
    showDialog: false,
    count: 1,
    radioCheckVal: 0,
    price: 0,
    selectedSpec: null,
    mobile: null,
    productId: '',
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "商品详情",
    })
    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        bind(options);
      }
    }
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo.mobile) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    wx.getUserInfo({
      success: res => {
        this.setData({
          nickName: res.userInfo.nickName,
        })
      }
    })

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })

    // this.setData({
    //   productId: options.productId
    // })
    network._post_json(this, api.getProductDetails, { productId: options.productId }, success);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    eventStatus = 0;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.product.title,
      path: '/pages/product/productDetails?shared=' + app.globalData.userAndTenantInfo.id + '&productId=' + this.data.product.id,
      // imageUrl: this.data.saleInfo.qrCode,
      success: function (res) {
        // 转发成功
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets,
            success: function (res) {
              network._post_json(this, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
            },
            fail: function (res) {
              // 转发失败
              network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
            }
          })
        } else {
          network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog,
      count: 1,
      radioCheckVal: 0
    })
    if(this.data.listSpec){
      spec: this.data.listSpec[0]
    }
    //allPrice(this, this.data.listSpec[0]);
    allPrice(this, this.data.product);
  },


  /**
   * 选择规格
   */
  radioCheckedChange: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      count: 1,
      radioCheckVal: index,
      selectedSpec: this.data.listSpec[index]
    })

    //allPrice(this, this.data.listSpec[e.detail.value]);
    allPrice(this, this.data.product);
  },

  /**
   * 进入下一步提交订单
   */
  next: function (e) {
    // var index = e.currentTarget.dataset.index;
    this.setData({
      showDialog: false,
      count: this.data.count
    });
    if (this.data.listSpec) {
      this.setData({
        selectedSpec: this.data.listSpec[this.data.radioCheckVal]
      });
    }

    if (eventStatus == 1) {
      addShoppingCart(this);
    } else if (eventStatus == 2) {
      startPay(this);
    }
  },


  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      this.setData({
        count: this.data.count
      });

      allPrice(this, this.data.product);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    this.data.count++;
    this.setData({
      count: this.data.count
    });

    allPrice(this, this.data.product);
  },

  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  chooseSpan: function (e) {
    var event = e.currentTarget.dataset.event;
    if (this.data.product.isVirtual == 0 && this.data.product.isActive == 1) {
      this.setData({
        showDialog: true,
      });
      eventStatus = event;
    } else {
      this.showZanTopTips('商品已下架');
    }
  },

  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },

  goshopcar: function (e) {
    wx.switchTab({
      url: '/pages/shoppingCar/shoppingCar',
    })
  }

}))

/**
 * 计算所选商品的总价
 */
var allPrice = function (that, item) {
  if (item.listSpec && item.listSpec.length > 0) {
    var spec = that.data.listSpec[that.data.radioCheckVal];
    that.setData({
      price: spec.price * that.data.count
    })
  } else {
    that.setData({
      price: item.price * that.data.count
    })
  }
}

// 获取商品列表结果
var success = function (that, res) {
  if (res.data.data) {
    that.setData({
      product: res.data.data.product,
      listSpec: res.data.data.product.listSpec,
    })
    WxParse.wxParse('details', 'html', res.data.data.product.productDetail.detail, that, 0);
    //if (that.data.product.listSpec) {
      allPrice(that, that.data.product);
    //}
  }
}

var addSuccess = function (that, res) {
  // that.setData({
  //   count: 1,
  //   radioCheckVal: 0,
  //   selectedSpec: that.data.listSpec[0]
  // })
  allPrice(that, that.data.product);
  that.showZanToast('添加成功');
}

var addShoppingCart = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    if (that.data.product.listSpec && that.data.product.listSpec.length > 0) {
      if (that.data.selectedSpec) {
        // 这里是把商品加入购物车的代码
        network._post_json(that, api.addShoppingCart, { product: { productId: that.data.product.id, specId: that.data.selectedSpec.id, count: that.data.count } }, addSuccess);
      }
    } else {
      // 没有规格的商品
      network._post_json(that, api.addShoppingCart, { product: { productId: that.data.product.id, count: that.data.count } }, addSuccess);
    }
  } else {
    that.showZanTopTips('商品已下架');
  }
}

var startPay = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    var product = {};
    var products = [];
    product.id = that.data.product.id;
    product.title = that.data.product.title;
    product.smallImgUrl = that.data.product.smallImgUrl;
    product.count = that.data.count;
    product.conMode = that.data.product.conMode
    // 这里是开始购买车的代码
    if (that.data.product.listSpec && that.data.product.listSpec.length > 0) {
      if (that.data.selectedSpec) {
        product.price = that.data.selectedSpec.price;
        product.specId = that.data.selectedSpec.id;
        product.specName = that.data.selectedSpec.name;
      }
    } else {
      // 没有规格的商品
      product.count = that.data.count;
      product.price = that.data.product.price;
    }
    products.push(product);
    try {
      wx.setStorageSync('products', products)
    } catch (e) {
    }

    allPrice(that, that.data.product);
    wx.navigateTo({
      url: '/pages/pay/pay'
    })
  } else {
    that.showZanTopTips('商品已下架');
  }
}

var bindSuccess = function (that, res) {
  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        productId: options.productId
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}